import genService from "@/api/services/tool/genService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import {
	DeleteOutlined,
	DownloadOutlined,
	EditOutlined,
	EyeOutlined,
	SyncOutlined,
	VerticalAlignBottomOutlined,
	VerticalAlignTopOutlined,
} from "@ant-design/icons";
import { Button, Card, Form, Input, Modal, Space, Table } from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import CodePreview from "./CodePreview";
import DbTableSelect, { type DbTableInfo } from "./dbtableSelect";
import GenModal from "./detail";
import type { GenTableColumn, TableInfo } from "./entity";

export default function GenPage() {
	const [form] = Form.useForm();
	const [loading, setLoading] = useState(false);
	const [data, setData] = useState<TableInfo[]>([]);
	const [total, setTotal] = useState(0);
	const [queryParams, setQueryParams] = useState({
		tableName: "",
		tableComment: "",
		page: 1,
		pageSize: 10,
	});
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingRecord, setEditingRecord] = useState<TableInfo | null>(null);
	const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");
	const [dbTableSelectVisible, setDbTableSelectVisible] = useState(false);
	const [codePreviewVisible, setCodePreviewVisible] = useState(false);
	const [previewTableName, setPreviewTableName] = useState<string>();

	// 表格列配置
	const columns: ColumnsType<TableInfo> = [
		{
			title: "表名称",
			dataIndex: "tableName",
			key: "tableName",
		},
		{
			title: "表描述",
			dataIndex: "tableComment",
			key: "tableComment",
		},
		{
			title: "实体类名称",
			dataIndex: "className",
			key: "className",
		},
		{
			title: "创建时间",
			dataIndex: "createTime",
			key: "createTime",
		},
		{
			title: "更新时间",
			dataIndex: "updateTime",
			key: "updateTime",
		},
		{
			title: "操作",
			key: "operation",
			width: 180,
			render: (_, record) => (
				<Space size="small">
					<Button
						type="link"
						icon={<EyeOutlined />}
						onClick={() => handlePreview(record)}
						style={{ padding: "5px 5px" }}
					>
						预览
					</Button>
					<Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)} style={{ padding: "5px 5px" }}>
						编辑
					</Button>
					<Button
						type="link"
						icon={<DeleteOutlined />}
						onClick={() => handleDelete(record)}
						style={{ padding: "5px 5px" }}
					>
						删除
					</Button>
					<Button type="link" icon={<SyncOutlined />} onClick={() => handleSync(record)} style={{ padding: "5px 5px" }}>
						同步
					</Button>
					<Button
						type="link"
						icon={<DownloadOutlined />}
						onClick={() => handleGenerate(record)}
						style={{ padding: "5px 5px" }}
					>
						生成代码
					</Button>
				</Space>
			),
		},
	];

	// 状态管理
	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => (col.key ? String(col.key) : "")),
	);

	// 处理过滤后的列配置
	const filteredColumns = columns.filter((col) => selectedValues.includes(String(col.key)) || col.key === "operation");

	// 模拟获取数据
	const fetchData = async () => {
		setLoading(true);

		await genService
			.pageList(queryParams)
			.then((res) => {
				setData(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(`获取数据失败：${error.message}`);
				toast.error("获取数据失败！");
			});

		setLoading(false);
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchData();
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [queryParams]);

	// 处理分页变化
	const handlePageChange = (page: number, pageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page,
			pageSize,
		}));
	};

	// 处理查询
	const handleSearch = (values: any) => {
		setQueryParams((prev) => ({
			...prev,
			...values,
			page: 1,
		}));
	};

	// 处理重置
	const handleReset = () => {
		form.resetFields();
		setQueryParams({
			tableName: "",
			tableComment: "",
			page: 1,
			pageSize: 10,
		});
	};

	/**
	 * 预览生成的代码
	 * @param record 行数据
	 */
	const handlePreview = (record: TableInfo) => {
		setCodePreviewVisible(true);
		setPreviewTableName(record.tableName);
	};

	/**
	 * 生成代码
	 * @param record 表信息
	 */
	const handleGenerate = (record: TableInfo) => {
		genService
			.download(record.tableName)
			.then((res) => {
				toast.success("生成代码成功");
			})
			.catch((error) => {
				console.error(error);
				toast.error("生成代码失败！");
			});
	};

	// 处理编辑
	const handleEdit = (record: TableInfo) => {
		setEditingRecord(record);
		setDrawerVisible(true);
	};

	// 处理删除
	const handleDelete = (record: TableInfo) => {
		Modal.confirm({
			title: "确认删除",
			content: `确定要删除表 "${record.tableName}" 吗？`,
			onOk: () => {
				// 这里应该是实际的删除API调用
				toast.success("删除成功");
				fetchData();
			},
		});
	};

	/**
	 * 同步表信息
	 * @param record 表信息
	 */
	const handleSync = (record: TableInfo) => {
		genService
			.synchDb(record.tableName)
			.then((res) => {
				toast.success(`同步表 ${record.tableName} 成功`);
				fetchData();
			})
			.catch((error) => {
				console.error(error);
				toast.error("同步失败！");
			});
	};

	// 处理批量删除
	const handleBatchDelete = () => {
		if (selectedRowKeys.length === 0) {
			toast.warning("请至少选择一条记录");
			return;
		}

		Modal.confirm({
			title: "确认删除",
			content: `确定要删除选中的 ${selectedRowKeys.length} 条记录吗？`,
			onOk: () => {
				// 这里应该是实际的批量删除API调用
				toast.success("批量删除成功");
				setSelectedRowKeys([]);
				fetchData();
			},
		});
	};

	// 处理保存
	const handleSave = async (formData: TableInfo, fieldData: GenTableColumn[]) => {
		const data = {
			...formData,
			columns: fieldData,
		};
		await genService
			.update(data)
			.then((res) => {
				toast.success(editingRecord ? "更新成功" : "新增成功");
			})
			.catch((error) => {
				console.log(error);
				toast.error("更新失败！", error);
			})
			.finally(() => {
				setDrawerVisible(false);
				fetchData();
			});
	};

	// 处理导入
	const handleImport = () => {
		setDbTableSelectVisible(true);
	};

	// 处理导出
	const handleExport = () => {
		const tables = selectedRowKeys.join(",");
		debugger;
		if (tables === "") {
			toast.warning("请至少选择一条记录");
			return;
		}
		genService
			.batchGenCode(tables)
			.then((res) => {
				toast.success("生成代码成功");
			})
			.catch((error) => {
				console.error(error);
				toast.error("生成代码失败！");
			});
	}

	// 处理导入确认
	const handleImportOk = (selectedTables: DbTableInfo[]) => {
		// 获取选中表的表名列表
		const tableNames = selectedTables.map((table) => table.tableName);

		// 调用后端接口导入表，将表名数组转换为逗号分隔的字符串
		genService
			.importTable({ tables: tableNames.join(",") })
			.then(() => {
				toast.success(`成功导入 ${selectedTables.length} 张表`);
				setDbTableSelectVisible(false);
				fetchData();
			})
			.catch((error) => {
				toast.error("导入表失败");
				console.error("导入表失败:", error);
			});
	};

	return (
		<div>
			{/* 查询条件 */}
			<Card className="mb-4">
				<Form form={form} layout="inline" onFinish={handleSearch}>
					<Form.Item name="tableName" label="表名称">
						<Input placeholder="请输入表名称" allowClear />
					</Form.Item>
					<Form.Item name="tableComment" label="表描述">
						<Input placeholder="请输入表描述" allowClear />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button className="ml-2" onClick={handleReset}>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			{/* 表格数据 */}
			<Card>
				<div className="flex justify-between mb-4">
					{/* 操作按钮 */}
					<div className="flex gap-2">
						<Button danger disabled={selectedRowKeys.length === 0} onClick={handleBatchDelete}>
							批量删除
						</Button>
						<Button type="primary" icon={<VerticalAlignBottomOutlined />} onClick={handleImport}>
							导入
						</Button>
						<Button icon={<VerticalAlignTopOutlined />} onClick={handleExport}>
							导出
						</Button>
					</div>
					<TableToolbar
						onRefresh={fetchData}
						onSizeChange={setTableSize}
						columns={columns}
						selectedValues={selectedValues}
						onColumnChange={setSelectedValues}
					/>
				</div>
				<Table
					rowKey="tableName"  // 修改为实际的唯一标识符字段
					size={tableSize}
					scroll={{ x: "max-content" }}
					loading={loading}
					pagination={{
						total,
						current: queryParams.page,
						pageSize: queryParams.pageSize,
						onChange: handlePageChange,
					}}
					columns={filteredColumns}
					dataSource={data}
					rowSelection={{
						type: "checkbox",
						selectedRowKeys: selectedRowKeys,
						onChange: (selectedKeys) => {
							setSelectedRowKeys(selectedKeys.map(key => key.toString()));
						},
					}}
				/>
			</Card>

			{/* 使用封装的模态框组件 */}
			<GenModal
				visible={drawerVisible}
				editingRecord={editingRecord}
				onCancel={() => setDrawerVisible(false)}
				onSave={handleSave}
			/>

			{/* 数据库表选择组件 */}
			<DbTableSelect
				visible={dbTableSelectVisible}
				onCancel={() => setDbTableSelectVisible(false)}
				onOk={handleImportOk}
			/>

			<CodePreview
				visible={codePreviewVisible}
				onCancel={() => setCodePreviewVisible(false)}
				tableName={previewTableName || ''}
			/>
		</div>
	);
}
